package ar.uba.fi.tonyvaliente.tree;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ar.uba.fi.tonyvaliente.files.RecordPosition;

/**
 * Referencia a un nodo en disco.
 * @author santiago
 *
 */
public class DiskBReference<K extends Comparable<K>, V> extends BReference<K, V> {

	private static Log log = LogFactory.getFactory().getInstance( DiskBReference.class );
	
	//private BTreeNode<K, V> node;

	private BTreeFileWrapper<K, V> wrapper;

	private RecordPosition recordPosition;
	
	public DiskBReference(BTreeFileWrapper<K, V> fileWrapper) {
		this.wrapper = fileWrapper;
	}

	public DiskBReference(BTreeNode<K, V> node) {
		this.node = node;
	}

	/* (non-Javadoc)
	 * @see ar.uba.fi.datos.tonyvaliente.tree.BReference#getNode()
	 */
	@Override
	public BTreeNode<K, V> getNode() throws BTreeException {
//		if(this.node == null){
			this.node = this.wrapper.getNode(this.recordPosition.getBlockNumber(), 
					this.recordPosition.getOffset()); 
			this.node.setThisReference(this);
//		}
		return this.node;
	}

	/* (non-Javadoc)
	 * @see ar.uba.fi.datos.tonyvaliente.tree.BReference#setNode(ar.uba.fi.datos.tonyvaliente.tree.BTreeNode)
	 */
	@Override
	public void setNode(BTreeNode<K, V> node) throws BTreeException {
		if(this.recordPosition == null){
			this.recordPosition = this.wrapper.appendNode(node);
			log.debug("appendNode devolvio: block: " + this.recordPosition.getBlockNumber()
					+ " - offset: " + this.recordPosition.getOffset());
		}else{
			this.updateNode();
		}
		this.node = node;
		this.node.setThisReference(this);

	}
	
	public RecordPosition getRecordPosition() {
		return recordPosition;
	}
	
	public void setRecordPosition(RecordPosition recordPosition) {
		this.recordPosition = recordPosition;
	}
	
	public void updateNode() throws BTreeException{
		this.wrapper.updateNode(node, this.recordPosition);
	}
	
	@Override
	public String toString() {
		return node.toString();
	}

}
